<script lang="ts" setup>
import type { CodeLoginInformationProps } from '@croco/framework/libraries';

import { ref } from 'vue';

import { AuthenticationCodeLogin } from '@croco/framework/libraries';
import { $t } from '@croco/framework/locales';

import VCodeLoginForm from '#/bean/code-login-form.vue';

defineOptions({ name: 'CodeLogin' });

const loading = ref(false);

const codeLoginFormRef = ref<InstanceType<typeof VCodeLoginForm>>();
const form = ref<CodeLoginInformationProps>({
    mobile: undefined,
    code: undefined,
});
const rules = ref({
    mobile: [
        { required: true, message: $t('authentication.mobileTip'), trigger: 'blur' },
        { pattern: /^1(3\d|4[014-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/, message: $t('authentication.mobileErrortip'), trigger: 'blur' },
    ],
    code: [{ required: true, message: $t('authentication.codeTip'), trigger: 'blur' }],
});

async function handleSubmit(): Promise<boolean> {
    return await codeLoginFormRef.value?.validate((status) => {
        if (status) {
            loading.value = true;
            // todo 登录
            console.warn('Send...');
        }
        return status;
    });
}

function handleSend(data: CodeLoginInformationProps) {
    // todo 通过手机号码发送验证
    console.warn(data);
}
</script>

<template>
    <AuthenticationCodeLogin :loading="loading" :submit="handleSubmit">
        <VCodeLoginForm ref="codeLoginFormRef" v-model="form" :rules="rules" @send="handleSend" />
    </AuthenticationCodeLogin>
</template>
